package com.hs.srm.admin.modules.pricemanagement.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hs.srm.admin.common.util.StringUtils;
import com.hs.srm.admin.modules.pricemanagement.entity.InquiryHeaderEntity;
import com.hs.srm.admin.modules.pricemanagement.entity.InquiryItemEntity;
import com.hs.srm.admin.modules.pricemanagement.entity.InquiryQuotationEntity;
import com.hs.srm.admin.modules.pricemanagement.entity.InquiryVendorEntity;
import com.hs.srm.admin.modules.pricemanagement.service.InquiryHeaderService;
import com.hs.srm.admin.modules.pricemanagement.service.InquiryItemService;
import com.hs.srm.admin.modules.pricemanagement.service.InquiryQuotationService;
import com.hs.srm.admin.modules.pricemanagement.service.InquiryVendorService;
import com.hs.srm.admin.modules.pricemanagement.vo.InquiryHeaderVO;
import com.hs.srm.admin.modules.pricemanagement.vo.InquiryVO;
import com.hs.srm.admin.modules.requisition.entity.*;
import com.hs.srm.admin.modules.requisition.service.*;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.config.SysConfig;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import sunnykid.text.SunnykidText;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * 询价抬头信息
 *
 * @author yanfei
 * @date 2019年1月14日
 */
@RestController
@RequestMapping("/inquiryHeader")
public class InquiryHeaderController extends AbstractController {

    private static final long serialVersionUID = -4123823577744890422L;

    @Autowired
    private InquiryHeaderService inquiryHeaderService;

    @Autowired
    private InquiryItemService inquiryItemService;
    @Autowired
    private InquiryVendorService inquiryVendorService;
    @Autowired
    private InquiryQuotationService inquiryQuotationService;
    @Autowired
    private ProPurchRequestHeaderService proPurchRequestHeaderService;
    @Autowired
    private ProPurchRequestItemService proPurchRequestItemService;

    @Autowired
    private NproPurchRequestHeaderService nproPurchRequestHeaderService;
    @Autowired
    private NproPurchRequestItemService nproPurchRequestItemService;

    @Autowired
    private SamplePurchRequestHeaderService sampleRequestHeaderService;
    @Autowired
    private SamplePurchRequestItemService samplePurchRequestItemService;

    // 文件存放的地址
    String savePath = "";
    String finalPath = "";

    /**
     * 保存询价单的信息
     *
     * @throws Exception
     */
    @SysLog("保存询价单的信息")
    @RequestMapping(value = "/save", produces = "application/json; utf-8")
    @Transactional(rollbackFor = Exception.class)
    public synchronized R save(@RequestBody JSONObject obj) {

        int item = 0;
        String data = obj.toJSONString();
        // Gson 日期格式话
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        InquiryVO inquiryVO = gson.fromJson(data, InquiryVO.class);
        // 询价单抬头
        InquiryHeaderEntity inquiryHeaderEntity = inquiryVO.getInquiryHeaderEntity();
        // 询价单行项目
        List<InquiryItemEntity> inquiryItemEntitylist = inquiryVO.getInquiryItemEntitylist();
        // 询价单行项目实体
        InquiryVendorEntity inquiryVendorEntity = null;
        // 询价单供应商
        List<VendorInfoEntity> vendorInfoEntitylist = inquiryVO.getVendorInfolist();
        // 询价供应商
        // InquiryVendorEntitylist inquiryVO
        List<InquiryVendorEntity> inquiryVendorEntitylist = new ArrayList<InquiryVendorEntity>();
        // 取出上传的文件list
        List<String> filestrlist = inquiryVO.getFilenames();
        //得到非生产性标识
        String flag = inquiryVO.getFlag();

        HashSet<String> requestCodeSet = new HashSet<String>();

        HashSet<String> npkIdSet = new HashSet<String>();

        // 维护三者的关系
        if (inquiryHeaderEntity != null && inquiryItemEntitylist != null && vendorInfoEntitylist.size() > 0) {
            // 询价单主键ID
            inquiryHeaderEntity.setInquiryId(SunnykidText.getUUID());
            String inquiryTotalCode = "";
            // 查询汇总号
            String inquiryTotalCodetem = selectnum();
            // 得到最大版本号
            int edition = selectversion();
            int suffix = 0;
            // 得到最大的汇总号  purchRequestCode
            if ("".equals(inquiryTotalCodetem) && edition == 0 || inquiryTotalCodetem == null) {
                inquiryTotalCode = StringUtils.makeStr("T", 0000000000, 10).replaceAll(" ", "0");
            } else {
                suffix = Integer.parseInt(inquiryTotalCodetem.substring(1));
            }
            //String requestCode = inquiryVO.getRequestCode();
            // 看版本号是否和查出来的一至
            if (suffix == edition) {
                edition++;
                suffix++;
                // 汇总号  T0000000069
                inquiryTotalCode = StringUtils.makeStr("T", suffix, 10).replaceAll(" ", "0");
                inquiryHeaderEntity.setInquiryTotalCode(inquiryTotalCode);// 汇总号
                inquiryHeaderEntity.setEdition(edition);
                ;// 版本更新
                //inquiryHeaderEntity.setRequestCode(requestCode);//采购申请编码
                for (InquiryItemEntity inquiryItem : inquiryItemEntitylist) {
                    item++;
                    inquiryItem.setNpkId(inquiryItem.getInquiryItemId());
                    inquiryItem.setInquiryItemId(SunnykidText.getUUID());
                    inquiryItem.setInquiryId(inquiryHeaderEntity.getInquiryId());// 外键ID 询价单Id
                    inquiryItem.setInquiryItemId(SunnykidText.getUUID());// 行项目主键
                    inquiryItem.setInquiryTotalCode(inquiryTotalCode); // 汇总号
                    inquiryItem.setInquiryItemCode(String.valueOf(item));// 可能递增
                    requestCodeSet.add(inquiryItem.getRequestCode());
                    npkIdSet.add(inquiryItem.getNpkId());//得到采购订单行项目id
                }
                for (VendorInfoEntity vendorInfo : vendorInfoEntitylist) {
                    inquiryVendorEntity = new InquiryVendorEntity();
                    //inquiryVendorEntity.setInquiryVendorId(vendorInfo.getPkId());// 需要找到对应的PkID;
                    inquiryVendorEntity.setInquiryVendorId(SunnykidText.getUUID());
                    inquiryVendorEntity.setInquiryId(inquiryHeaderEntity.getInquiryId()); // 询价单ID 这个在批量提交时自动生成
                    inquiryVendorEntity.setInquiryTotalCode(inquiryTotalCode);// 汇总号
                    inquiryVendorEntity.setVendorCode(vendorInfo.getSapCode());// SAP 编码
                    inquiryVendorEntity.setVendorName(vendorInfo.getVendorName());// 供应商名称
                    inquiryVendorEntity.setTaxCode(vendorInfo.getTaxCode());// 税代码
                    inquiryVendorEntity.setFlag(flag);//非生产性与生产性标识
                    inquiryVendorEntity.setPayTermsPurchase(vendorInfo.getPayCondition());// 付款条款
                    inquiryVendorEntity.setI18nTradeTerms(vendorInfo.getI18nTradeTerms());// 国际贸易条框
                    inquiryVendorEntitylist.add(inquiryVendorEntity);
                }
                this.inquiryHeaderService.insert(inquiryHeaderEntity);
                this.inquiryItemService.insertBatch(inquiryItemEntitylist);
                for (InquiryVendorEntity inquiryVendor : inquiryVendorEntitylist) {
                    this.inquiryVendorService.insert(inquiryVendor);
                }
                for (String str : requestCodeSet) {
                    //非生产性
                    if (("PR").equals(str.trim().substring(0, 2))) {
                        NproPurchRequestHeaderEntity nproPurchRequestHeaderEntity = this.nproPurchRequestHeaderService.findByNo(str);
                        //订单已询价
                        nproPurchRequestHeaderEntity.setGoodsStatus(-1);
                        if (nproPurchRequestHeaderEntity != null) {
                            this.nproPurchRequestHeaderService.insertOrUpdate(nproPurchRequestHeaderEntity);
                            for (String pkId : npkIdSet) {
                                NproPurchRequestItemEntity nproPurchRequestItemEntity = this.nproPurchRequestItemService.selectById(pkId);
                                nproPurchRequestItemEntity.setGoodsStatus(-1);
                                this.nproPurchRequestItemService.insertOrUpdate(nproPurchRequestItemEntity);
                            }
                        }
                    } else if (str.trim().indexOf("S") >= 0) {
                        SamplePurchRequestHeaderEntity sampleHeader = sampleRequestHeaderService.selectOne(new EntityWrapper<SamplePurchRequestHeaderEntity>().eq("purch_request_code", str));
                        //样品
                        if (sampleHeader != null) {
                            //订单已询价
                            sampleHeader.setGoodsStatus(-1);
                            sampleRequestHeaderService.insertOrUpdate(sampleHeader);
                            for (String pkId : npkIdSet) {
                                SamplePurchRequestItemEntity sampleItemEntity = samplePurchRequestItemService.selectById(pkId);
                                sampleItemEntity.setGoodsStatus(-1);
                                samplePurchRequestItemService.insertOrUpdate(sampleItemEntity);
                            }
                        }
                    } else {
                        ProPurchRequestHeaderEntity proPurchRequestHeaderEntity = proPurchRequestHeaderService.findByNo(str);
                        //生产性
                        if (proPurchRequestHeaderEntity != null) {
                            //订单已询价
                            proPurchRequestHeaderEntity.setGoodsStatus(-1);
                            boolean b = this.proPurchRequestHeaderService.insertOrUpdate(proPurchRequestHeaderEntity);
                            for (String pkId : npkIdSet) {
                                ProPurchRequestItemEntity proPurchRequestItemEntity = this.proPurchRequestItemService.selectById(pkId);
                                proPurchRequestItemEntity.setGoodsStatus(-1);
                                boolean c = this.proPurchRequestItemService.insertOrUpdate(proPurchRequestItemEntity);
                            }
                        } else {
                            return R.msg("新增失败");
                        }
                    }
                }
            } else {
                return R.msg("新增失败");
            }
        }
        //询价后生成报价单，省去生成报价单步骤
        InquiryHeaderEntity headerEntity = inquiryHeaderService.selectOne(new EntityWrapper<InquiryHeaderEntity>().eq("inquiry_total_code", inquiryHeaderEntity.getInquiryTotalCode()));
        return insertBatch(JSONObject.toJSON(headerEntity).toString());
    }

    /**
     * 查询供应商信息
     */

    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        // 查询用户列表
        SysUserEntity username = this.getUser();
        if (username.getDeptId() == 13) {
            params.put("username", username.getUsername());
        }
        PageUtils page = inquiryHeaderService.queryPage(params);
        List<InquiryHeaderEntity> list = (List<InquiryHeaderEntity>) page.getList();
        list = EntityUtils.valToTxt(list);
        page.setList(list);
        return R.ok(page);
    }

    /**
     * 跳转至供应商编辑页面
     *
     * @param
     * @return
     */
    @RequestMapping("/toEdit/{inquiryId}")
    public ModelAndView toEdit(@PathVariable("inquiryId") String inquiryid) {
        InquiryHeaderEntity inquiryHeaderEntity = this.inquiryHeaderService.selectById(inquiryid);
        // InquiryItemEntity inquirtemEntity = this.inquiryItemService.selectById(inquiryid);

        String inquiryTotalCode = inquiryHeaderEntity.getInquiryTotalCode();
        List<InquiryItemEntity> itemlist = this.inquiryItemService.findByNo(inquiryTotalCode);
        List<InquiryVendorEntity> vendorlist = this.inquiryVendorService.findByNo(inquiryTotalCode);

		/*if(itemlist!=null){
			for(NproPurchRequestItemEntity ite : itemlist){
				//subjectCategory
				if("K".equals(ite.getSubjectCategory())){
					ite.setSubjectCategory("K-成本中心");
				}
				if("A".equals(ite.getSubjectCategory())){
					ite.setSubjectCategory("A-固定资产");
				}
				if("F".equals(ite.getSubjectCategory())){
					ite.setSubjectCategory("F-在建工程");
				}
			}
		}*/
        // 把查询出来的对象赋值给供应商实体
        ModelAndView modelAndView = new ModelAndView("modules/pricemanagement/inquiry/inquiry_edit");
        modelAndView.addObject("inquiryHeaderEntity", inquiryHeaderEntity);
        modelAndView.addObject("itemlist", itemlist);
        modelAndView.addObject("vendorlist", vendorlist);
        return modelAndView;

		/*//把查询出来的对象赋值给供应商实体
		ModelAndView modelAndView = new ModelAndView("modules/pricemanagement/inquiry/inquiry_edit");
		modelAndView.addObject("inquiryHeaderEntity", inquiryHeaderEntity);
		modelAndView.addObject("inquirtemEntity", inquirtemEntity);
		return modelAndView;*/
    }

    /**
     * 查询最大版本号
     */
    @SysLog("查询版本号")
    @RequestMapping("/selectnum")
    public String selectnum() {
        return this.inquiryHeaderService.selectnum();
    }

    /**
     * 查询最大汇总号
     */
    @SysLog("查询最大汇总号")
    @RequestMapping("/selectversion")
    public int selectversion() {
        return this.inquiryHeaderService.selectversion();
    }

    /**
     * 产生报价单
     */
    @SuppressWarnings("unused")
    @SysLog("产生报价单")
    @RequestMapping("/insertBatch")
    @ResponseBody
    // @RequiresPermissions("inquiryHeader:insertBatch")
    public synchronized R insertBatch(@RequestBody String param) {
        // 创建一个JSONObject对象，返回数据ResponseBody用
        JSONObject jsonObject = JSONObject.parseObject(param);
        // json字符数据转成list

        //询价后直接生成报价单，省去生成报价单步骤，（生成报价单页可多选生成）
        //List<String> list = JSONArray.parseArray(jsonObject.getString("inquiryId"), String.class);
        //用list是为了不改变此前代码
        List<String> list = Arrays.asList(jsonObject.getString("inquiryId"));

        // 根据询价单id查询对应的抬头(查出两笔数据)
        List<InquiryHeaderVO> inquiryHeaderlist = inquiryHeaderService.selectBatchIds(list);
        InquiryQuotationEntity inquiryQuotationEntity = null;
        List<InquiryQuotationEntity> entityList = null;
        // 查询报价单号
        String inquiryCode = inquiryQuotationService.selectnum();
        // 得到最大版本号
        String edition = inquiryQuotationService.selectversion();

        int suffix = 0;
        // 生成报价单号
        String prefix = "Q-" + DateUtils.format(DateUtils.currentDateTime(), "yyyyMM");
        if (edition == null && inquiryCode == null && edition == null) {
            entityList = new ArrayList<InquiryQuotationEntity>();
            for (InquiryHeaderVO inquiryHeaderVO : inquiryHeaderlist) {
                inquiryQuotationEntity = new InquiryQuotationEntity();
                suffix++;
                String inquiryTotalCode = StringUtils.makeStr(prefix, suffix, 3).replaceAll(" ", "0");//报价单号
                inquiryQuotationEntity.setQuotationId(SunnykidText.getUUID());//主键id
                inquiryQuotationEntity.setInquiryCode(inquiryTotalCode);
                inquiryQuotationEntity.setInquiryId(inquiryHeaderVO.getInquiryId());// 询价单号
                inquiryQuotationEntity.setInquiryTotalCode(inquiryHeaderVO.getInquiryTotalCode());// 汇总号
                /**********************询价修改********************************/
                inquiryQuotationEntity.setInquiryItemId(inquiryHeaderVO.getInquiryItemId());// 行项目id
                inquiryQuotationEntity.setInquiryItemCode(inquiryHeaderVO.getInquiryItemCode());// 行号
                inquiryQuotationEntity.setEdition(inquiryTotalCode);
                //inquiryTotalCode
                inquiryQuotationEntity.setRequestCode(inquiryHeaderVO.getRequestCode()); // 采购申请单号
                inquiryQuotationEntity.setNpkId(inquiryHeaderVO.getNpkId()); //采购订单行项目id
                inquiryQuotationEntity.setInquiryVendorId(inquiryHeaderVO.getInquiryVendorId());// 询价供应商id
                inquiryQuotationEntity.setVendorCode(inquiryHeaderVO.getVendorCode());// 供应商编码
                inquiryQuotationEntity.setVendorName(inquiryHeaderVO.getVendorName()); // 供应商名称
                //新增供应商税代码
                inquiryQuotationEntity.setTaxCode(inquiryHeaderVO.getTaxCode()); // 新增供应商税代码


                inquiryQuotationEntity.setCurrency(inquiryHeaderVO.getCurrency());//币种
                inquiryQuotationEntity.setWerks(inquiryHeaderVO.getWerks()); //工厂
                inquiryQuotationEntity.setMaterialCode(inquiryHeaderVO.getMaterialCode()); //物料编码
                inquiryQuotationEntity.setMaterialDesc(inquiryHeaderVO.getMaterialDesc()); //物料描述
                inquiryQuotationEntity.setPurchaseGrp(inquiryHeaderVO.getPurchaseGrp()); //采购组
                inquiryQuotationEntity.setPurchaseOrg(inquiryHeaderVO.getPurchaseOrg()); //采购组织
                inquiryQuotationEntity.setMaterialGroup(inquiryHeaderVO.getMaterialGroup());// 物料组
                inquiryQuotationEntity.setCompCode(inquiryHeaderVO.getCompanyCode());//公司代码

                inquiryQuotationEntity.setState(-1);//报价单未提交

                entityList.add(inquiryQuotationEntity);
                /**********************询价修改********************************/
            }
        } else {
            if (edition.equals(inquiryCode) || edition == null) {
                entityList = new ArrayList<InquiryQuotationEntity>();
                suffix = Integer.parseInt(inquiryCode.substring(inquiryCode.length() - 3, inquiryCode.length()));
                for (InquiryHeaderVO inquiryHeaderVO : inquiryHeaderlist) {
                    inquiryQuotationEntity = new InquiryQuotationEntity();
                    InquiryQuotationEntity inquiryQuotation = inquiryQuotationService
                            .selectByNameInquiryTotalCode(inquiryHeaderVO.getInquiryTotalCode());
                    if (inquiryQuotation == null || !inquiryQuotation.getInquiryTotalCode().equals(inquiryHeaderVO.getInquiryTotalCode())) {
                        suffix++;
                        String inquiryTotalCode = StringUtils.makeStr(prefix, suffix, 3).replaceAll(" ", "0"); //报价单号
                        inquiryQuotationEntity.setQuotationId(SunnykidText.getUUID());
                        inquiryQuotationEntity.setInquiryCode(inquiryTotalCode);
                        inquiryQuotationEntity.setInquiryId(inquiryHeaderVO.getInquiryId());// 询价单号
                        inquiryQuotationEntity.setInquiryTotalCode(inquiryHeaderVO.getInquiryTotalCode());// 汇总号

                        inquiryQuotationEntity.setRequestCode(inquiryHeaderVO.getInquiryTotalCode()); // 采购申请单号
                        inquiryQuotationEntity.setNpkId(inquiryHeaderVO.getNpkId()); //采购订单行项目id
                        /*************************询价修改**************************/

                        inquiryQuotationEntity.setInquiryItemId(inquiryHeaderVO.getInquiryItemId());// 行项目id
                        inquiryQuotationEntity.setInquiryItemCode(inquiryHeaderVO.getInquiryItemCode());// 行号
                        inquiryQuotationEntity.setRequestCode(inquiryHeaderVO.getRequestCode()); // 采购申请单号
                        inquiryQuotationEntity.setInquiryVendorId(inquiryHeaderVO.getInquiryVendorId());// 询价供应商id
                        inquiryQuotationEntity.setVendorCode(inquiryHeaderVO.getVendorCode());// 供应商编码
                        inquiryQuotationEntity.setVendorName(inquiryHeaderVO.getVendorName()); // 供应商名称
                        inquiryQuotationEntity.setEdition(inquiryTotalCode);// 版本号
                        inquiryQuotationEntity.setCurrency(inquiryHeaderVO.getCurrency());//币种
                        inquiryQuotationEntity.setWerks(inquiryHeaderVO.getWerks()); //工厂

                        inquiryQuotationEntity.setMaterialCode(inquiryHeaderVO.getMaterialCode()); //物料编码
                        inquiryQuotationEntity.setMaterialDesc(inquiryHeaderVO.getMaterialDesc()); //物料描述
                        inquiryQuotationEntity.setPurchaseGrp(inquiryHeaderVO.getPurchaseGrp()); //采购组
                        inquiryQuotationEntity.setPurchaseOrg(inquiryHeaderVO.getPurchaseOrg()); //采购组织
                        inquiryQuotationEntity.setMaterialGroup(inquiryHeaderVO.getMaterialGroup());// 物料组
                        inquiryQuotationEntity.setState(-1);//报价单未提交

                    }
                    entityList.add(inquiryQuotationEntity);
                }
            }
        }
        if (entityList != null && entityList.size() > 0) {
            boolean b = inquiryQuotationService.insertBatch(entityList);
            if (b) {
                for (String st : list) {
                    InquiryHeaderEntity inquiryHeaderEntity = this.inquiryHeaderService.selectById(st);
                    inquiryHeaderEntity.setState(InquiryHeaderEntity.STATE_BAOJIADANYICHANSHENG);
                    boolean c = this.inquiryHeaderService.updateById(inquiryHeaderEntity);
                    if (!c) {
                        return R.msg("批量提交失败");
                    }
                }
            }
        } else {
            return R.msg("批量提交失败");
        }
        return R.ok();
    }

    /**
     * 更新询价单信息
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json; utf-8")
    public R update(@RequestBody JSONObject obj) {
        if (obj != null) {
            String inquiryHeader = obj.get("inquiryHeaderEntity").toString();
            InquiryHeaderEntity inquiryHeaderEntity = JSONObject.parseObject(inquiryHeader, InquiryHeaderEntity.class);
            this.inquiryHeaderService.updateById(inquiryHeaderEntity);
        }
        return R.ok();
    }

    /**
     * 批量附件上传
     */
    @RequestMapping(value = "/uploadBatch", method = RequestMethod.POST, produces = "application/json; utf-8")
    public @ResponseBody
    String uploadBatch(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        // 上传（导入）文件存放路径
        File baseDir = new File(SysConfig.getUploadPath());
        if (!baseDir.exists() || !baseDir.isDirectory()) {
            baseDir.mkdirs();
        }
        // getOriginalFilename()是得到上传时的文件名。
        // String savePath = "D:\\MultipartFile\\";
        if (files != null && files.length != 0) {
            if (null != files && files.length > 0) {
                // 遍历并保存文件
                for (MultipartFile file : files) {
                    savePath = SysConfig.getUploadPath() + File.separator + System.currentTimeMillis()
                            + file.getOriginalFilename();
                    System.out.println("文件上传地址：" + savePath);
                    try {
                        file.transferTo(new File(savePath));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "success";
    }

}
